package study.week05.gateway.backend;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

/**
 * 这里创建amq的监听者模拟后端服务.<br/>
 * 这里的监听者,在监听到消息后,会做业务处理,然后将返回值也放到amq中.<br/>
 * 在实际开发中，监听者和生产者不会放在同一个服务中，这里是简化版本，仅演示效果.
 */
@Component
public class AmqBackendServer {
    @Autowired
    JmsTemplate jmsTemplate;
    private String serverName01 = "server01";
    private String response01 = serverName01 +".response";

    private String serverName02 = "server02";
    private String response02 = serverName02 +".response";
    /**
     * 模拟Backend服务监听队列  1
     */
    @JmsListener(destination = "server01.request")
    public void getQueue1(String info) {
        System.out.println(serverName01 +" receive:"+info);
        //截取请求的UID,然后将uid拼接后响应
        String[] split = info.split(":");
        String uid = split[0];
        jmsTemplate.send(response01, session -> {
            return session.createTextMessage(uid+":"+ response01+","+System.currentTimeMillis());
        });
    }


    /**
     * 模拟Backend服务监听队列  2
     */
    @JmsListener(destination = "server02.request")
    public void getQueue2(String info) {
        System.out.println(serverName02 +" receive:"+info);
        //截取请求的UID,然后将uid拼接后响应
        String[] split = info.split(":");
        String uid = split[0];
        jmsTemplate.send(response02, session -> {
            return session.createTextMessage(uid+":"+ response02+","+System.currentTimeMillis());
        });
    }

}
